//
//  NetDownloadBooks+SeparateDown.m
//  KidReading
//
//  Created by linziyuan on 16/12/27.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "NetDownloadBooks+SeparateDown.h"
#import "ConstDefine.h"

@implementation NetDownloadBooks (SeparateDown)

+ (void)load {
    [self swizzleSelector:@selector(downBooksUrl:relIndex:delegate:withBookID:edition:withThroughDict:) withSelector:@selector(sqDownBooksUrl:relIndex:delegate:withBookID:edition:withThroughDict:)];
    [self swizzleSelector:@selector(downSuccessOpreationWithBookDownInfo:) withSelector:@selector(spDownSuccessOpreationWithBookDownInfo:)];
}

- (void)sqDownBooksUrl:(NSArray *)urlStrArr relIndex:(NSArray *)numArr delegate:(id<NetDownloadBooksDelegate>)delegate withBookID:(NSInteger)bookid edition:(long long)edition withThroughDict:(NSDictionary *)throughDict {
    [DataProcessing do_Async_quick:^{
        for (BookDownInfo* bookdowninfo in downingBooksInfoArr) {
            if (bookdowninfo.bookid == bookid) {
                //
                NSLog(@"正在下载 %d 不可重复下载",(int)bookid);
                return;
            }
        }
        //准备下载通知
        for (NSValue* value in noticeDelegateArr) {
            id<NetDownloadBooksNotice> notice = [value nonretainedObjectValue];
            if ([notice respondsToSelector:@selector(netNotice_ReadyDownloadBook:)]) {
                [DataProcessing do_Main_quick:^{
                    [notice netNotice_ReadyDownloadBook:bookid];
                }];
            }
        }
        //
        TABLE_BOOKS *tbBook = [throughDict valueForKey:@"TB_Book"];
        NSInteger count = urlStrArr.count;
        BookDownInfo* bookdowninfo = [[BookDownInfo alloc] init];
        [downingBooksInfoArr addObject:bookdowninfo];
        bookdowninfo.zipCount = count;
        bookdowninfo.bookid = bookid;
        bookdowninfo.bookEdition = edition;
        bookdowninfo.listInfo = [tbBook listInfo];
        [downingBooksInfoArr addObject:bookdowninfo];
        bookdowninfo.zipsStatus = [[NSMutableString alloc] initWithCapacity:count];
        for (NSInteger n=0; n<count; n++) {
            [bookdowninfo.zipsStatus appendString:@"0"];
        }
        for (NSInteger i =0; i<count; i++) {
            NSDictionary *urlItem = [urlStrArr objectAtIndex:i];
            NSString* urlpath = [urlItem valueForKey:@"uri"];
            NSString* urlEdtion = [urlItem valueForKey:@"edition"];
            NSInteger realIndex = i;
            if (numArr && i < numArr.count) {
                realIndex = [numArr[i] integerValue];
            }
            //
            if ([self spIsDowneForBook:bookid urlPath:urlpath edition:[urlEdtion longLongValue] readSource:tbBook.readSource originID:tbBook.originalId]) {
                @synchronized(self){
                    [bookdowninfo addpercentage:1.0/bookdowninfo.zipCount];
                }
                NSInteger xx = 0;
                for (NSInteger n =0; n<i; n++) {
                    xx += 1;
                }
                [bookdowninfo.zipsStatus replaceCharactersInRange:NSMakeRange(xx, 1) withString:@"1"];
                bookdowninfo.countDownSuccess += 1;
                //通知状态，需要解压成功
                NSInteger bookid = bookdowninfo.bookid;
                for (NSValue* value in noticeDelegateArr) {
                    id<NetDownloadBooksNotice> notice = [value nonretainedObjectValue];
                    if ([notice respondsToSelector:@selector(netNotice_DownloadBookFinishedOneZipIndex:bookID:)]) {
                        [DataProcessing do_Main_quick:^{
                            [notice netNotice_DownloadBookFinishedOneZipIndex:realIndex bookID:bookid];
                        }];
                    }
                    if ([notice respondsToSelector:@selector(netNotice_DownloadBookFinishedOneZipIndex:bookID:throughDict:)]) {
                        [DataProcessing do_Main_quick:^{
                            [notice netNotice_DownloadBookFinishedOneZipIndex:realIndex bookID:bookid throughDict:throughDict];
                        }];
                    }
                }
                continue;
            }else{
                [[CacheData shareSingle] updateDowningBook:bookid infoItem:urlItem];
            }
            //
            NSMutableDictionary* dict = [NSMutableDictionary new];
            if (throughDict) [dict setObject:throughDict forKey:__throughDict__];
            [dict setObject:bookdowninfo forKey:@"BookDownInfo"];
            [dict setObject:delegate forKey:@"delegate"];
            //
            zipDownInfo* zipdowninfo = [[zipDownInfo alloc] init];
            zipdowninfo.zipDownPercentage = 0;
            zipdowninfo.zipIndex = i;
            zipdowninfo.relZipIndex = realIndex;
            [dict setObject:zipdowninfo forKey:@"zipDownInfo"];
            //
            NSURL* url = [NSURL URLWithString:[DataProcessing fullBookZipFileUrl:urlpath]];
            
            NSString* tempPath = [DataProcessing tempZipPathForBookID:bookid urlPath:urlpath];
            NSString* zipPath = [DataProcessing storeZipPathForBookID:bookid urlPath:urlpath];
            //
            zipdowninfo.zipPath = zipPath;
            JRASIHTTPRequest* asihttprequest = [JRASIHTTPRequest requestWithURL:url];
            asihttprequest.tag = bookid;
            [asihttprequest setTemporaryFileDownloadPath:tempPath];
            [asihttprequest setDownloadDestinationPath:zipPath];
            [asihttprequest setUserInfo:dict];
            [asihttprequest setDelegate:self];
            [asihttprequest setDownloadProgressDelegate:self];
            [asihttprequest setAllowResumeForFileDownloads:NO];//开关断点下载
            [asihttprequest setTimeOutSeconds:120];//设置单个包最大允许120秒下载时长
            [asihttprequest setShouldContinueWhenAppEntersBackground:YES];//后台继续下载
            //[asihttprequest startAsynchronous];
            @synchronized (@"queDown") {
                [self queDown:asihttprequest];
            }
        }
    }];
}


- (BOOL)spIsDowneForBook:(NSInteger)bookid urlPath:(NSString*)urlpath edition:(long long)edition readSource:(NSString *)readSource originID:(NSInteger)originID
{
    long long bookEdition = [[CacheData shareSingle] getEditionForDownIngBook:bookid url:urlpath];
    if(bookEdition == edition){
        NSString* zipPath = [DataProcessing storeZipPathForBookID:bookid urlPath:urlpath];
        if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath]) {
            bool ret = NO;
            if ([readSource isEqualToString:@"quiz"]) {
                ret = [DataProcessing unZipTalkZipPath:zipPath forOriginalID:originID];
            }else {
               ret = [DataProcessing unZipBookZipPath:zipPath forBookid:bookid];
            }
            
#if __IsToKeepLocalZip == 0
            if(!ret)[[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];
#endif
            return ret;
        }
    }else{
        NSString* zipPath = [DataProcessing storeZipPathForBookID:bookid urlPath:urlpath];
        if ([[NSFileManager defaultManager] fileExistsAtPath:zipPath]) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];
            });
        }
    }
    return NO;
}

-(void)spDownSuccessOpreationWithBookDownInfo:(BookDownInfo *)bookdowninfo
{
    [[CacheData shareSingle] updateBook:bookdowninfo.bookid CacheInfoData:bookdowninfo.listInfo];
    UserInfo* uinfo = [[CacheData shareSingle] getUserLoginInfo];
    [[CacheData shareSingle] updateBook:bookdowninfo.bookid CacheInfoData:bookdowninfo.listInfo forUid:uinfo.uid];
    [downingBooksInfoArr removeObject:bookdowninfo];
}

- (NSNumber *)unZipQuizPathWithZipPath:(NSString *)zipPath tbBook:(TABLE_BOOKS *)tbBook {
    BOOL reuslt = NO;
    if ([tbBook.readSource isEqualToString:@"quiz"]) {
        reuslt = [DataProcessing unZipQuizBookZipPath:zipPath forBookOriginal:tbBook.originalId];
    }else{
        reuslt = [DataProcessing unZipBookZipPath:zipPath forBookid:tbBook.bookId];
    }
    return @(reuslt);
}

@end
